<?php
/**
 * Created by PhpStorm.
 * User: thorjiang
 * Date: 2018/5/9
 * Time: 17:09
 */

namespace App\Http\Middleware;

use Closure;
use App\Models\UserModel;
use Illuminate\Support\Facades\Redis;

class MicroAppAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $token = $request->header('token');
        // 验证token是否有效, 从redis里获取
        $user = UserModel::where('open_id', $token)->first();

        if (empty($user)) {
            return getErrorResponse(CODE_B_ACCOUNT_NEED_LOGIN, '账户需要登录');
        }

        if ($user->status != 0) {
            throwResponseException(2, "您已被封号（ID：{$user->id}），请联系工作人员");
        }

        $request->attributes->set('user_id', $user['id']);
        $request->attributes->set('user', $user);

        return $next($request);
    }
}
